//
//  Controller.m
//  iDent
//
//  Created by Marius Corega on 3/24/09.
//  Copyright 2009 __MyCompanyName__. All rights reserved.
//

#import "Controller.h"
#import "Pacienti.h"
#import "Fisa.h"
#import "Manopere.h"
#import "Foto.h"
#import "FotoView.h"


#define TBOpen @"TBOpen"
#define TBFisaView @"TBFisaView"
#define TBDatePersonaleView @"TBDatePersonleView"
#define TBFotoView @"TBFotoView"
#define TBRxView @"TBRxView"
#define TBModelView @"TBModelView"
#define TBDiagnosticView @"TBDiagnosticView"
#define TBTratamentView @"TBTratamentView"
#define TBSearchView @"TBSearchView"



@implementation Controller

-(void) resetLoadedTabs
{
	isDPLoaded = isFisaLoaded = isFotoLoaded = isRxLoaded = isModelLoaded = isDiagnosticLoaded = isTratamentLoaded = NO;
	
}

- (BOOL)applicationShouldTerminateAfterLastWindowClosed:(NSApplication *)theApplication
{
	return YES;
}

- (void)applicationWillTerminate:(NSNotification *)aNotification
{
	[pacienti unlockElements];
	[fisa unlockElements];
	[diagnostic unlockElements];
	[poze unlockElements];
}

- (void)applicationWillFinishLaunching:(NSNotification *)aNotification
{
    // this creates our custom document controller. see
    // SPDocumentController.h for more details on how the
    // subclass is used.    
    
   // _foto = [NSArray array];
}

- (id) init
{
	self = [super init];

	dataTrans = [[DatatoDataView alloc] init];
	[NSValueTransformer setValueTransformer:dataTrans forName:@"dataTransformer"];
//	NSMutableArray *aa = [NSMutableArray arrayWithCapacity:10];
//	fisaMA = aa;
	pozaSelectata = @"";
	playingDirty = NO;
	return self;
}

-(void) manopereLoaded
{
	[manopereAC setContent:[manopere manopereStrings]];
}

-(void) tipFotoLoaded
{
	[tipFotoAC setContent:[tipFoto tipuriStrings]];
}

-(void) fisaLoaded
{
	NSString* fisaID = nil;
	
	if([fisaAC selectionIndex] != NSNotFound) fisaID = [[[fisaAC selectedObjects] objectAtIndex:0] valueForKey:@"id"];
	
	[fisaAC setContent:[fisa fisa]];
	
	if(fisaID) [fisaAC setSelectedObjects:[NSArray arrayWithObjects:[fisa elementWithID:fisaID], nil]];
	[deplataManopera setStringValue: [[NSNumber numberWithInt:[fisa calculeazaDePlatit]] stringValue] ];
}

-(void) pacientiLoaded
{
	NSString *pacientID = nil;
	
	if ([pacienti selectedElement] != nil)
	{
		pacientID = [[pacienti selectedElement] objectForKey:@"id"];
		//[pacientID retain];
	}
	
	//[pacientiAC setContent:[pacienti pacienti]];
	[self setPac:[pacienti pacienti]];
	//[pacientiAC setContent:[pacienti pacienti]];
	
	if (pacientID != nil)
	{
		for (int i=0; i<[[pacienti pacienti] count]; i++)
		{
			NSDictionary *selPacient = [[pacienti pacienti] objectAtIndex:i];
			
			NSString *id = [selPacient objectForKey:@"id"];
			if([id isEqualToString:pacientID]) [pacientiAC setSelectedObjects:[NSArray arrayWithObjects: selPacient, nil]];
		}
		[pacientID release];
	}
	else if([[pacienti pacienti] count]>0)
	{
		[listaPacienti selectRow:0 byExtendingSelection:NO];
	}
}

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
    // this creates our custom document controller. see
    // SPDocumentController.h for more details on how the
    // subclass is used.    
    
	// _foto = [NSArray array];
	/*
	NSDictionary *info = [[NSBundle mainBundle] infoDictionary];
	
	NSString *ver = [info valueForKey:@"CFBundleVersion"];
	NSNumberFormatter *nf = [[NSNumberFormatter alloc] init];
	int v = [[nf numberFromString:ver] intValue];
	ver = [[[NSString alloc] initWithData:[self loadServerURL:@"version.php"] encoding:NSASCIIStringEncoding] autorelease] ;
	int sv = [[nf numberFromString:ver] intValue];
	
	if(sv > v)
	{
		NSAlert *alerta = [NSAlert alertWithMessageText:@"O versiune mai noua a programului este disponibila!" defaultButton:@"Da" alternateButton:@"Nu" otherButton:@"" informativeTextWithFormat:@"Doriti sa o descarcati?"];	
		
		if([alerta runModal])
		{
			[[NSWorkspace sharedWorkspace] launchApplication:@"Safari"];
		}
			
	}
	*/
	[self showLogin:self];
	[username setStringValue:@"vasile"];
	[password setStringValue:@"vasile"];
	//[self login];

	
	[pacientiAC addObserver:self forKeyPath:@"selectedObjects" options: NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:nil];
	//[manopere addObserver:self forKeyPath:@"_elemente" options:NSKeyValueObservingOptionNew context:nil];
	//[self addObserver:self forKeyPath:@"nume" options:   NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:nil];
	
	[[NSNotificationCenter defaultCenter] addObserver:self
											 selector:@selector(manopereLoaded)
												 name:@"ManopereLoaded" object:nil];

	[[NSNotificationCenter defaultCenter] addObserver:self
											 selector:@selector(pacientiLoaded)
												 name:@"PacientiLoaded" object:nil];

	[[NSNotificationCenter defaultCenter] addObserver:self
											 selector:@selector(tipFotoLoaded)
												 name:@"TipFotoLoaded" object:nil];

	[[NSNotificationCenter defaultCenter] addObserver:self
											 selector:@selector(fisaLoaded)
												 name:@"FisaLoaded" object:nil];
	
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id) object change:(NSDictionary *)change context:(void *)context
{
//	NSLog(@"%@",change);
//	NSLog(@"%@",object);
	if((object == pacientiAC) && ([keyPath isEqualToString:@"selectedObjects"]))
	{
		if([[object selectedObjects] count]>0)
		{
			NSMutableDictionary* sel = [[object selectedObjects] objectAtIndex:0];
			//NSLog(@"%@",sel);
			
			[pacienti setSelectedElement:sel];	

			NSInteger selIdx = [listaPacienti selectedRow];
			[pacientiAC removeObserver:self forKeyPath:@"selectedObjects"];
			[pacienti reloadElementWithID:[sel objectForKey:@"id"]];
			playingDirty = YES;
			[listaPacienti selectRow:selIdx byExtendingSelection:NO];

			if(![datePersonaleView isHidden])
			{
				//[self setDatePersonale];
				isDPLoaded = YES;
				//[listaPacienti reloadData];
			}
			else if (![fisaView isHidden])
			{
				[fisa unlockElements];
				[self loadFisaForPacient:[[pacienti selectedElement] objectForKey:@"id"]];
				//[self setFisa];
				
			}
			else if(![fotoView isHidden])
			{
				[self loadFotoForPacient:[sel objectForKey:@"id"] forceReload:NO];
				
			}
			else if(![dgView isHidden])
			{
				
				[self loadDgForPacient:[[pacienti selectedElement] objectForKey:@"id"]];
				
			}
			
			[pacientiAC addObserver:self forKeyPath:@"selectedObjects" options:   NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:nil];
		}
	}	
	else 
	if (object == manopere) {

		[manopereAC setContent:manopere];
	}
	
}

-(void)awakeFromNib
{
	
	[self resetLoadedTabs];
	
	[contentView addSubview:datePersonaleView];
	[contentView addSubview:fisaView];
	[contentView addSubview:fotoView];
	[contentView addSubview:rxView];
	[contentView addSubview:dgView];
	[contentView addSubview:modelView];
	
	[datePersonaleView setFrame:NSMakeRect(0, 0, [contentView frame].size.width , [contentView frame].size.height)];
	[fisaView setFrame:NSMakeRect(0, 0, [contentView frame].size.width , [contentView frame].size.height)];
	[rxView setFrame:NSMakeRect(0, 0, [contentView frame].size.width , [contentView frame].size.height)];
	[fotoView setFrame:NSMakeRect(0, 0, [contentView frame].size.width , [contentView frame].size.height)];
	[dgView setFrame:NSMakeRect(0, 0, [contentView frame].size.width , [contentView frame].size.height)];
	[modelView setFrame:NSMakeRect(0, 0, [contentView frame].size.width , [contentView frame].size.height)];

	
	NSToolbar *tb = [[NSToolbar alloc] initWithIdentifier:@"ass"] ;
	[tb setDelegate:self];	
	[tb setAllowsUserCustomization:YES];
	[tb setAutosavesConfiguration:YES];
	[tb setDisplayMode:NSToolbarDisplayModeIconAndLabel];
	
	//[tb setVisible:YES];
	
	[window setToolbar:[tb autorelease]];
	[datePersonaleView setHidden:NO];
	[fisaView setHidden:YES];
	[fotoView setHidden:YES];
	[rxView setHidden:YES];
	[dgView setHidden:YES];
	[modelView setHidden:YES];
	
	
}

-(NSData*) loadServerURL: (NSString*) URL 
{
	NSURLResponse *resp;
	NSError *err = NULL;
	NSMutableString *srvURL = [[NSMutableString alloc] initWithString:serverURL];
	
	[srvURL appendString:URL];
	
	NSURLRequest *reg = [NSURLRequest requestWithURL:[NSURL URLWithString: srvURL]];	
	
	[progressIndicator startAnimation:self];
	NSData *data = [NSURLConnection sendSynchronousRequest:reg returningResponse:&resp error:&err ];
	[progressIndicator stopAnimation:self];
	[debug setStringValue:srvURL];
	if(err)  [[NSApplication sharedApplication] presentError:err];
	
	NSLog(srvURL);
	NSLog(@"%@", [[[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding] autorelease]);
	
	
	return data;
}

-(void) postServer:(id) sender
{
	
}

-(NSData*) postServerURL:(NSString*) URL withDict:(NSDictionary*) dict 
{

	NSData* regData = [self generateFormData:dict];
	NSURLResponse* response;
	NSError* error;
	NSMutableString *srvURL = [[NSMutableString alloc] initWithString:serverURL];
	
	[srvURL appendString:URL];
	
	
	NSMutableURLRequest* post = [NSMutableURLRequest requestWithURL: [NSURL URLWithString:srvURL]];
	[post addValue: @"multipart/form-data; boundary=_insert_some_boundary_here_" forHTTPHeaderField: @"Content-Type"];
	[post setHTTPMethod: @"POST"];
	[post setHTTPBody:regData];

	[progressIndicator startAnimation:self];
	NSData* result = [NSURLConnection sendSynchronousRequest:post returningResponse:&response error:&error];
	NSLog(@"%@", [[[NSString alloc] initWithData:result encoding:NSASCIIStringEncoding] autorelease]);
	[progressIndicator stopAnimation:self];
	
	return result;
}

-(NSData*) postServerURLAsync:(NSString*) URL withDict:(NSDictionary*) dict selector:(SEL)selector
{
	
	 NSData* regData = [self generateFormData:dict];
	 NSURLResponse* response;
	 NSError* error;
	 NSMutableString *srvURL = [[NSMutableString alloc] initWithString:serverURL];
	 
	 [srvURL appendString:URL];
	
	 
	 NSMutableURLRequest* post = [NSMutableURLRequest requestWithURL: [NSURL URLWithString:srvURL]];
	 [post addValue: @"multipart/form-data; boundary=_insert_some_boundary_here_" forHTTPHeaderField: @"Content-Type"];
	 [post setHTTPMethod: @"POST"];
	 [post setHTTPBody:regData];
	 
	 [progressIndicator startAnimation:self];
	 NSData* result = [NSURLConnection sendSynchronousRequest:post returningResponse:&response error:&error];
	 NSLog(@"%@", [[[NSString alloc] initWithData:result encoding:NSASCIIStringEncoding] autorelease]);
	 [progressIndicator stopAnimation:self];
	 
	NSMutableDictionary *postDict = [NSMutableDictionary dictionaryWithDictionary:dict];
	[postDict setObject:URL forKey:@"url"];
//	[postDict setObject:selector forKey:@"selector"];
	[self performSelectorInBackground:@selector(postServer) withObject:nil];
	
	return result;
}


-(BOOL)login
{
	medic = [[Medic alloc] initWithServerURL:[NSURL URLWithString:serverURL]];
	medic.username = [username stringValue];
	medic.password = [password stringValue];
	[medic load];
	
	NSString *rez =[[medic medic] objectForKey:@"id"];
	NSInteger res = [rez intValue];
	
	if(res > 0)
	{
		
		[self loadPacienti];
		
		[self loadManopere];
		[self loadTipFoto];
		
	//	timer = [NSTimer timerWithTimeInterval:10.0f target:self selector:@selector(timerFireMethod:) userInfo:nil repeats:YES];
	//	[[NSRunLoop currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];

		
		unlockTimer = [NSTimer timerWithTimeInterval:60.0f target:self selector:@selector(unlockTimerFireMethod:) userInfo:nil repeats:YES];
		[[NSRunLoop currentRunLoop] addTimer:unlockTimer forMode:NSDefaultRunLoopMode];

		return YES;
	}
	return NO;
}


-(void) setDatePersonale
{
	if(isDPLoaded) return;
	
	NSMutableDictionary *pacient = [pacienti selectedElement];
	
	[nume setStringValue:[pacient objectForKey:@"nume"]];
	[prenume setStringValue:[pacient objectForKey:@"prenume"]];
	[adresa setStringValue:[pacient objectForKey:@"adresa"]];
	[cnp setStringValue:[pacient objectForKey:@"cnp"]];
	[telefon setStringValue:[pacient objectForKey:@"telefon"]];
	[mobil setStringValue:[pacient objectForKey:@"mobil"]];
	[email setStringValue:[pacient objectForKey:@"email"]];
	[cse setStringValue:[pacient objectForKey:@"cse"]];
	[dataIncepere setDateValue:[NSDate dateWithNaturalLanguageString:[pacient objectForKey:@"dataincepere"]]];
	[dataTerminare setDateValue:[NSDate dateWithNaturalLanguageString:[pacient objectForKey:@"dataterminare"]]];
	
	isDPLoaded = YES;
	
}


#pragma mark -
#pragma mark Loaders

-(void) loadTipFoto
{
	
	tipFoto = [[TipFoto alloc]initWithServerURL:[NSURL URLWithString:serverURL]];
	[tipFoto loadAsync];
	
	[tipFotoAC setContent:[tipFoto tipuriStrings]];
	
}

-(void) loadManopere
{
	manopere = [[Manopere alloc] initWithServerURL:[NSURL URLWithString:serverURL]]; 
	[manopere loadAsync];
	
	//[manopereAC setContent:[manopere manopereStrings]];
	
}



-(IBAction) reloadData:(id)sender
{
	//[listaPacienti reloadData];	
}


#pragma mark -
#pragma mark Fisa Handler

-(void) loadFisaForPacient:(NSString*)pacientID
{
	
	NSString* fisaID = nil;
	
	if([fisaAC selectionIndex] != NSNotFound) fisaID = [[[fisaAC selectedObjects] objectAtIndex:0] valueForKey:@"id"];
	
	if(!fisa) fisa = [[Fisa alloc] initWithServerURL:[NSURL URLWithString:serverURL]];

	[fisa loadForPacientWithIDAsync:pacientID];	
		
	/*
	[fisaAC setContent:[fisa fisa]];
	
	if(fisaID) [fisaAC setSelectedObjects:[NSArray arrayWithObjects:[fisa elementWithID:fisaID], nil]];
	[deplataManopera setStringValue: [[NSNumber numberWithInt:[fisa calculeazaDePlatit]] stringValue] ];
	 */
}

-(IBAction) addFisa:(id)sender
{
	/*
	[self loadServerURL:[NSString stringWithFormat:@"adaugafisa.php?id=%@&pacientid=%@", 
						 [[[manopere manopere] objectAtIndex: [tipManopera indexOfSelectedItem]] objectForKey:@"id"], [pacient objectForKey:@"id"]]];
	 */

	NSMutableDictionary* post_dict = [NSMutableDictionary dictionary];
	NSDictionary* manopera = [[manopere manopere] objectAtIndex: [tipManoperaNou indexOfSelectedItem]];
	
	[post_dict setObject: [[pacienti selectedElement] objectForKey:@"id"] forKey:@"pacientid"];
	
	[post_dict setObject:[descriereManoperaNou stringValue]/*[selFisa objectForKey:@"mentiuni"]*/ forKey:@"mentiuni"];
	[post_dict setObject:[[DatatoDataView alloc] reverseTransformedValue:[dataManoperaNou dateValue]] forKey:@"data"];
	
	[post_dict setObject:[manopera objectForKey:@"cod"] forKey:@"cod"];
	[post_dict setObject:[manopera objectForKey:@"descriere"] forKey:@"descriere"];
	[post_dict setObject:[manopera objectForKey:@"pret"] forKey:@"pret"];
	
	NSString* fisaID = [fisa addElement:post_dict];
	[fisaAC setSelectedObjects:[NSArray arrayWithObjects:[fisa elementWithID:fisaID], nil]];
	
	isFisaLoaded = NO;
	[self setFisa];
}

-(IBAction) stergeFisa:(id)sender
{
	NSAlert *alerta = [NSAlert alertWithMessageText:@"Doriti stergerea inregistrarii selectate?" defaultButton:@"Da" alternateButton:@"Nu" otherButton:@"" informativeTextWithFormat:@""];	
	
	if([alerta runModal])
	{
		[fisa removeElementWithID:[[fisa selectedElement] objectForKey:@"id"]];
		isFisaLoaded = NO;
		[self setFisa];
	}
}

-(IBAction) updateTabelFisa:(id)sender
{
	NSMutableDictionary *selFisa = [[fisaAC selectedObjects] objectAtIndex:0];
	//NSString* fisaID = [selFisa objectForKey:@"id"];

	/*
	NSInteger tag = [sender tag];
	NSString *title = nil;	
	
	if (tag == 1) title = @"pret";
	else if (tag == 2) title = @"achitat";
	else if (tag == 3) title = @"nr_fact";
	else if (tag == 4) 
	{
		[fisa setElementWithID:fisaID value:[descriereManopera stringValue] forField:@"mentiuni"];
	}
	else if (tag == 5)
	{
		[fisa setElementWithID:fisaID value:[dataManopera stringValue] forField:@"data"];
	}
	else if (tag == 6)
	{
		[fisa setElementWithID:fisaID value:[[[manopere manopere] objectAtIndex: [tipManopera indexOfSelectedItem]] objectForKey:@"descriere"] forField:@"descriere"];
	}
	
	if(title != nil)
	{
		[fisa setElementWithID:fisaID value:[selFisa objectForKey:title] forField:title];
	}
*/
	[selFisa setObject:[descriereManopera stringValue] forKey:@"mentiuni"];
	[fisa setElement:selFisa];
	[deplataManopera setStringValue: [[NSNumber numberWithInt:[fisa calculeazaDePlatit]] stringValue] ];
}


-(IBAction) updateFisa:(id)sender
{
	/*
	NSDictionary *selFisa = [[fisaAC selectedObjects] objectAtIndex:0];
	NSMutableDictionary* post_dict = [[NSMutableDictionary alloc] init];	
	
	[post_dict setObject:[selFisa objectForKey:@"id"] forKey:@"id"];

	[post_dict setObject:[descriereManopera stringValue]/*[selFisa objectForKey:@"mentiuni"]*//* forKey:@"mentiuni"];
	[post_dict setObject:[dataManopera stringValue] forKey:@"data"];
	[post_dict setObject:[pretManopera stringValue] forKey:@"pret"];
	[post_dict setObject:[platitManopera stringValue] forKey:@"achitat"];
	[post_dict setObject:[nrfacturaManopera stringValue] forKey:@"nr_fact"];
	[post_dict setObject:[[[manopere manopere] objectAtIndex: [tipManopera indexOfSelectedItem]] objectForKey:@"id"] forKey:@"idman"];
	
	[self postServerURL:@"modificafisa.php" withDict:post_dict];
	[post_dict release];
	[deplataManopera setStringValue: [[NSNumber numberWithInt:[fisa calculeazaDePlatit]] stringValue] ];
*/
}


-(void) setFisa
{
	if(isFisaLoaded) return;
	
	[self loadFisaForPacient:[[pacienti selectedElement] objectForKey:@"id"]];
	//[listaFisa reloadData];

	
	isFisaLoaded = YES;
}

#pragma mark -
#pragma mark Diagnostic Handler

-(void) loadDgForPacient:(NSString*)pacientID
{	
	if(! diagnostic) diagnostic = [[Diagnostic alloc] initWithServerURL:[NSURL URLWithString:serverURL]];
	
	if(diagnostic) [diagnostic unlockElementWithID:[[[diagnostic diagnostic] objectAtIndex:0] valueForKey:@"id" ]];
	[diagnostic loadForPacientWithID:pacientID];
	if(diagnostic) [diagnostic lockElementWithID:[[[diagnostic diagnostic] objectAtIndex:0] valueForKey:@"id" ]];
	
	[diagnosticDC setContent:[diagnostic diagnostic]];
	[diagnosticDC setSelectionIndex:0];

}

-(IBAction) updateDiagnostic:(id)sender
{
	NSDictionary *dg = [[diagnostic diagnostic] objectAtIndex:0];
	
	//[self postServerURL:@"updatediagnostic.php" withDict:dg];
	[diagnostic setElement:dg];
	
}

#pragma mark -
#pragma mark Pacient Handler


-(void) loadPacienti
{
	NSString *pacientID = nil;
	
	if ([pacienti selectedElement] != nil)
	{
		pacientID = [[pacienti selectedElement] objectForKey:@"id"];
		[pacientID retain];
	}
	
	[progressIndicator startAnimation:nil];
	if (pacienti ==nil)
	{
		pacienti = [[Pacienti alloc] initWithServerURL:[NSURL URLWithString:serverURL]];
		pacienti.medicID = [[medic medic] objectForKey:@"id"];
		
	}
	[pacienti loadAsync];
	[progressIndicator stopAnimation:nil];
/*	
	[self setPac:[pacienti pacienti]];
	//[pacientiAC setContent:[pacienti pacienti]];
	
	if (pacientID != nil)
	{
		for (int i=0; i<[[pacienti pacienti] count]; i++)
		{
			NSDictionary *selPacient = [[pacienti pacienti] objectAtIndex:i];
			
			NSString *id = [selPacient objectForKey:@"id"];
			if([id isEqualToString:pacientID]) [pacientiAC setSelectedObjects:[NSArray arrayWithObjects: selPacient, nil]];
		}
		[pacientID release];
	}
	else if([[pacienti pacienti] count]>0)
	{
		[listaPacienti selectRow:0 byExtendingSelection:NO];
	}
 */
}

-(IBAction) addPacient:(id)sender
{
	NSMutableDictionary* dict = [NSMutableDictionary dictionary];
	[dict setObject:[[medic medic] objectForKey:@"id"] forKey:@"medic"];
	[dict setObject:@"nume" forKey:@"nume"];
	[dict setObject:@"prenume" forKey:@"prenume"];
	
	NSString* pacientID = [pacienti addElement:dict];
	[diagnostic addForPacientWithID:pacientID];
	
	[self loadPacienti];
		
	for (int i=0; i<[[pacienti pacienti] count]; i++)
	{
		NSDictionary *selPacient = [[pacienti pacienti] objectAtIndex:i];

		NSString *pid = [selPacient objectForKey:@"id"];
		if([pid isEqualToString:pacientID]) [pacientiAC setSelectedObjects:[NSArray arrayWithObjects: selPacient, nil]];
	}	
}


-(IBAction) updatePacient:(id)sender
{
	/*
	[pacient setValue:[nume stringValue] forKey:@"nume"];
	[pacient setValue:[prenume stringValue] forKey:@"prenume"];
	[pacient setValue:[cnp stringValue] forKey:@"cnp"];
	[pacient setValue:[adresa stringValue] forKey:@"adresa"];
	[pacient setValue:[telefon stringValue] forKey:@"telefon"];
	[pacient setValue:[mobil stringValue] forKey:@"mobil"];
	[pacient setValue:[email stringValue] forKey:@"email"];
	[pacient setValue:[cse stringValue] forKey:@"cse"];
	[pacient setValue:[dataIncepere stringValue] forKey:@"dataincepere"];
	[pacient setValue:[dataTerminare stringValue] forKey:@"dataterminare"];
	*/	
	
	[pacienti setElementWithID:[[pacienti selectedElement] valueForKey:@"id"]];
}

-(IBAction) stergePacient:(id) sender
{
	NSAlert *alerta = [NSAlert alertWithMessageText:@"Doriti stergerea pacientului selectat?" defaultButton:@"Da" alternateButton:@"Nu" otherButton:@"" informativeTextWithFormat:@""];
	
	if([alerta runModal])
	{
		[pacienti removeElementWithID:[[pacienti selectedElement] objectForKey:@"id"]];
		[self loadPacienti];
	}
}

#pragma mark -
#pragma mark TableView delegates


- (void)tableViewSelectionDidChange:(NSNotification *)aNotification
{
	if([aNotification object] == listaPacienti)
	{
		[self resetLoadedTabs];
		if([[pacienti pacienti] count]>0)
		{
			
		}
	}
	
	else if([aNotification object] == listaFisa)
	{
		
		if([[fisa fisa] count]>0)
		{
			
			if([[fisaAC selectedObjects] count]>0)
			{
				[fisa setSelectedElement:[[fisaAC selectedObjects] objectAtIndex:0]];
				
				NSString* fisaID = [[fisa selectedElement] objectForKey:@"id"];
				[fisa reloadElementWithID:fisaID];
				[deplataManopera setStringValue: [[NSNumber numberWithInt:[fisa calculeazaDePlatit]] stringValue] ];
			}
			else [fisa setSelectedElement:nil];
				
		
		}	
	}
	
	
}

- (id)tableView:(NSTableView *)aTableView
objectValueForTableColumn:(NSTableColumn *)aTableColumn
			row:(int)rowIndex
{
    id theRecord, theValue;
	
	if(aTableView == listaPacienti)
	{
		
		NSParameterAssert(rowIndex >= 0 && rowIndex < [[pacienti pacienti] count]);
		theRecord = [[pacienti pacienti] objectAtIndex:rowIndex];
		theValue = [theRecord objectForKey:[aTableColumn identifier]];
	}
	else if(aTableView == listaFisa)
	{
		NSParameterAssert(rowIndex >= 0 && rowIndex < [[fisa fisa] count]);
		theRecord = [[fisa fisa] objectAtIndex:rowIndex];
		theValue = [theRecord objectForKey:[aTableColumn identifier]];
		
	}

	
	return theValue;
}

- (int)numberOfRowsInTableView:(NSTableView *)aTableView
{
    int count = 0;
	
	if(aTableView == listaPacienti) count = [[pacienti pacienti] count];
	else if(aTableView == listaFisa) count = [[fisa fisa] count];

	return count;
}

#pragma mark -
#pragma mark Toolbar delegates

-(NSArray *)toolbarSelectableItemIdentifiers:(NSToolbar *)toolbar
{
	return [NSArray arrayWithObjects:TBOpen, TBFisaView, TBDatePersonaleView, TBFotoView, TBRxView, TBModelView, TBDiagnosticView, nil];
}

- (NSArray *)toolbarAllowedItemIdentifiers:(NSToolbar*)toolbar
{
    return [NSArray arrayWithObjects:NSToolbarSeparatorItemIdentifier,
			NSToolbarSpaceItemIdentifier,
			NSToolbarFlexibleSpaceItemIdentifier,
			NSToolbarCustomizeToolbarItemIdentifier, 
			@"AddItem", @"RemoveItem", @"SearchItem", TBOpen, TBFisaView, TBDatePersonaleView, TBFotoView, TBRxView, TBModelView,TBDiagnosticView, TBSearchView, nil];
}

- (NSArray *)toolbarDefaultItemIdentifiers:(NSToolbar*)toolbar
{
    return [NSArray arrayWithObjects: 
			NSToolbarFlexibleSpaceItemIdentifier, TBDatePersonaleView, TBFisaView, TBFotoView, TBRxView, TBModelView,TBDiagnosticView,
			NSToolbarFlexibleSpaceItemIdentifier,  TBSearchView, nil];
}

- (NSToolbarItem *) toolbar:(NSToolbar *)toolbar
      itemForItemIdentifier:(NSString *)itemIdentifier
  willBeInsertedIntoToolbar:(BOOL)flag
{
    NSToolbarItem *toolbarItem = [[NSToolbarItem alloc] initWithItemIdentifier: itemIdentifier];
	
	if([itemIdentifier isEqualToString:TBOpen])
	{
		[toolbarItem setLabel:@"Deschide"];
		[toolbarItem setToolTip:@"Deschide"];
		[toolbarItem setPaletteLabel:@"Deschide"];
		[toolbarItem setTarget:self];
		[toolbarItem setAction:@selector(deschideDoc:)];
		
	}
	else if([itemIdentifier isEqualToString:TBFisaView])
	{
		[toolbarItem setLabel:@"Fisa"];
		[toolbarItem setToolTip:@"Arata fisa"];
		[toolbarItem setPaletteLabel:@"Fisa"];
		[toolbarItem setTarget:self];
		[toolbarItem setAction:@selector(arataFisa:)];
		[toolbarItem setImage:[NSImage imageNamed:@"NSFolderSmart"]];
		
	}
	else if([itemIdentifier isEqualToString:TBDatePersonaleView])
	{
		[toolbarItem setLabel:@"Date personale"];
		[toolbarItem setToolTip:@"Arata datele personale"];
		[toolbarItem setPaletteLabel:@"Date personale"];
		[toolbarItem setTarget:self];
		[toolbarItem setAction:@selector(arataDatePersonale:)];
		[toolbarItem setImage:[NSImage imageNamed:@"NSUser"]];
		
	}
	else if([itemIdentifier isEqualToString:TBFotoView])
	{
		[toolbarItem setLabel:@"Fotografii"];
		[toolbarItem setToolTip:@"Arata fotograiile pacientului"];
		[toolbarItem setPaletteLabel:@"Fotografii"];
		[toolbarItem setTarget:self];
		[toolbarItem setAction:@selector(arataFoto:)];
		[toolbarItem setImage:[NSImage imageNamed:@"Poze.icns"]];
		
	}
	else if([itemIdentifier isEqualToString:TBRxView])
	{
		[toolbarItem setLabel:@"Radiografii"];
		[toolbarItem setToolTip:@"Arata radiografiile pacientului"];
		[toolbarItem setPaletteLabel:@"Radiografii"];
		[toolbarItem setTarget:self];
		[toolbarItem setAction:@selector(arataRx:)];
		[toolbarItem setImage:[NSImage imageNamed:@"rx.tif"]];
		
	}
	else if([itemIdentifier isEqualToString:TBDiagnosticView])
	{
		[toolbarItem setLabel:@"Diagnostic"];
		[toolbarItem setToolTip:@"Arata diagnosticul pacientului"];
		[toolbarItem setPaletteLabel:@"Diagnostic"];
		[toolbarItem setTarget:self];
		[toolbarItem setAction:@selector(arataDg:)];
		[toolbarItem setImage:[NSImage imageNamed:@"dg.tif"]];
		
	}
	else if([itemIdentifier isEqualToString:TBModelView])
	{
		[toolbarItem setLabel:@"Model"];
		[toolbarItem setToolTip:@"Arata modelul pacientului"];
		[toolbarItem setPaletteLabel:@"Model"];
		[toolbarItem setTarget:self];
		[toolbarItem setAction:@selector(arataModel:)];
		[toolbarItem setImage:[NSImage imageNamed:@""]];		
	}
	else if([itemIdentifier isEqualToString:TBSearchView])
	{
		[toolbarItem setLabel:@"Cauta"];
		[toolbarItem setToolTip:@"Cauta pacienti"];
		[toolbarItem setPaletteLabel:@"Cauta"];
		[toolbarItem setTarget:self];
		//[toolbarItem setAction:@selector(arataModel:)];
		//[toolbarItem setImage:[NSImage imageNamed:@""]];		
		[toolbarItem setView: searchView];
        
       // [toolbarItem setMinSize:NSMakeSize(30, NSHeight([searchView frame]))];
       // [toolbarItem setMaxSize:NSMakeSize(400,NSHeight([searchView frame]))];
		
	}
	else 
	{
		toolbarItem = nil;
	}

	
    return toolbarItem;
}

#pragma mark -
#pragma mark Foto Handler

-(NSData*) loadThumb:(NSString*)pictureid
{
	static NSMutableDictionary *thumbCache = nil;
	NSData *data = nil;
	
	if(!thumbCache) thumbCache = [[NSMutableDictionary alloc] init];
	
	data=[thumbCache objectForKey:pictureid];
	
	if(!data) 
	{
		NSMutableString *srvURL = [[NSMutableString alloc] init];
		
		[srvURL appendString:@"thumb.php?pid="];
		[srvURL appendString:pictureid];
	
		data = [self loadServerURL:srvURL];
		[thumbCache setObject:data forKey:pictureid];
	}
	
	return data;
}

-(NSData*) loadFotoMare:(NSString*)pictureid
{
	static NSMutableDictionary *thumbCache = nil;
	NSData *data = nil;
	
	if(!thumbCache) thumbCache = [[NSMutableDictionary alloc] init];
	
	data=[thumbCache objectForKey:pictureid];
	
	if(!data) 
	{
		NSMutableString *srvURL = [[NSMutableString alloc] init];
		
		[srvURL appendString:@"poza.php?pid="];
		[srvURL appendString:pictureid];
		
		data = [self loadServerURL:srvURL];
		[thumbCache setObject:data forKey:pictureid];
	}
	
	return data;
}


-(void)loadFoto:(NSString *)pacientID
{
	NSInteger thumb_width = 80;
	//NSMutableString *srvURL = [NSMutableString string];
	NSString* pozaID = nil;
	
	if([pozeAC selectionIndex] != NSNotFound) pozaID = [[[pozeAC selectedObjects] objectAtIndex:0] valueForKey:@"id"];
	
	if(!poze) poze = [[Poze alloc] initWithServerURL:[NSURL URLWithString:serverURL]];
	
	//poze.grupSelectat = @"toate";
	[poze loadForPacientWithID:pacientID];	
	[pozeAC setContent:[poze poze]];
	
	//if(pozaID) [pozeAC setSelectedObjects:[NSArray arrayWithObjects:[poze elementWithID:pozaID], nil]];
	
	NSInteger nr_foto = [[poze poze]count];	
	NSMutableArray *oldfoto = foto;
	foto = [[NSMutableArray alloc] init];
	
	[listaFotoView setFrame:NSMakeRect(0,0,nr_foto * thumb_width, thumb_width)];
	
	for (NSInteger i=0; i<nr_foto; i++)
	{
		NSDictionary *dict = [[poze poze]objectAtIndex:i];
		
		NSData *data = [self loadThumb:[dict objectForKey:@"id"]];
		
		Foto *f = [[Foto alloc] init];
		f.thumb = [[NSImage alloc]initWithData:data ];
		//f.image = f.thumb;
		f.nume = [NSString stringWithFormat:@"foto:%d",i];
		
		[foto addObject:f]; 
		//[data release];
		
	}	
	
	listaFotoView.fotos = foto;
	[listaFotoView loadFotos];
	//[oldfoto removeAllObjects];
	[oldfoto release];
	//[fotoAC setContent: foto];
	//[pozeAC setContent:[poze poze]];
	if([[poze poze] count]<1) [poze setSelectedElement:nil];
	
	if(nr_foto > 0)
	{
		[self arataFotocuID:0];
	}
	else {
		[fotoMare setNoImage];
	}	
}

-(void) loadFotoForPacient:(NSString *)pacientID forceReload:(BOOL)forceReload
{
	if((![[[poze selectedElement] objectForKey:@"pacientid"] isEqualToString:pacientID])||(forceReload))
	{
		[poze setGrupSelectat:@"toate"];
		[self loadFoto:pacientID];
		NSMutableArray *g = [poze grupPoze];
		[grupPozeAC setContent:g];
		//[grupPozeAC setSelectedObjects:[NSArray arrayWithObjects:[g objectAtIndex:[g count] -1],nil]];
		[grupPozePB selectItemAtIndex:[g count]-1];
	}
}

-(BOOL)arataFotocuID:(NSInteger)nr
{
	NSLog([NSString stringWithFormat:@"foto id:%i", nr]);
	BOOL ret = NO;
	
	Foto *f = [foto objectAtIndex:nr];
	NSMutableDictionary *dict = [[poze poze]objectAtIndex:nr];
	
	if(dict != [poze selectedElement])
	{
		[poze reloadElementWithID:[dict objectForKey:@"id"]];
		
		if(!f.imageData)
		{
			NSDictionary *dict = [[poze poze]objectAtIndex:nr];
			NSData *data = [self loadFotoMare:[dict objectForKey:@"id"]];
			
			//f.image = [[NSImage alloc]initWithData:data ];
			NSImage* img = [[NSImage alloc]initWithData:data ];
			f.imageData = [img TIFFRepresentation];
			[img release];
		}
		
		[fotoMare setImageData:f.imageData];
		
		ret = [fotoAC setSelectionIndex:nr];
		[pozeAC setSelectedObjects:[NSArray arrayWithObject:dict]];
		[poze setSelectedElement:dict];
	}
	return ret;
}

-(IBAction) stergeFoto:(id) sender
{
	NSAlert *alerta = [NSAlert alertWithMessageText:@"Doriti stergerea fotografiei selectate?" defaultButton:@"Da" alternateButton:@"Nu" otherButton:@"" informativeTextWithFormat:@""];
	
	if(![pozaSelectata isEqualToString:@""])
		if([alerta runModal])
		{
			[poze removeElementWithID:[[poze selectedElement] objectForKey:@"id"]];
			[self loadFotoForPacient:[[pacienti selectedElement] objectForKey:@"id"] forceReload:YES];
		}
}

-(IBAction) updateFoto:(id)sender
{
	NSDictionary *selFoto = [[pozeAC selectedObjects] objectAtIndex:0];
	/*
	CGPoint p = [fotoMare origin];
	[selFoto setValue:[[NSNumber numberWithInt:p.x] stringValue] forKey:@"originex"];
	[selFoto setValue:[[NSNumber numberWithInt:p.y] stringValue] forKey:@"originey"];
	[selFoto setValue:[[NSNumber numberWithInt:[fotoMare tipFoto]] stringValue] forKey:@"tip"];
	[selFoto setValue:[fotoMare descriereFoto] forKey:@"descriere"];
	[selFoto setValue:[fotoMare dataFoto] forKey:@"data"];
	
	*/
	[poze setElement:selFoto];NSLog(@"%@", selFoto);
}


#pragma mark -
#pragma mark Actions

-(void)arataDatePersonale:(id)sender
{
	[datePersonaleView setHidden:NO];
	[fotoView setHidden:YES];
	[rxView setHidden:YES];
	[fisaView setHidden:YES];
	[dgView setHidden:YES];
	[modelView setHidden:YES];
	[self setDatePersonale];
	[zoomSlider setHidden:YES];
}

-(void)arataFisa:(id)sender
{
	[datePersonaleView setHidden:YES];
	[fotoView setHidden:YES];
	[rxView setHidden:YES];
	[fisaView setHidden:NO];
	[dgView setHidden:YES];
	[modelView setHidden:YES];
	[zoomSlider setHidden:YES];
	[self setFisa];
}

-(void)arataFoto:(id)sender
{
	[datePersonaleView setHidden:YES];
	[fisaView setHidden:YES];
	[rxView setHidden:YES];
	[fotoView setHidden:NO];
	[dgView setHidden:YES];
	[modelView setHidden:YES];
	[zoomSlider setHidden:NO];
	[self loadFotoForPacient:[[pacienti selectedElement] objectForKey:@"id"] forceReload:YES];
}


-(void)arataRx:(id)sender
{
	[datePersonaleView setHidden:YES];
	[fisaView setHidden:YES];
	[rxView setHidden:NO];
	[fotoView setHidden:YES];
	[dgView setHidden:YES];
	[modelView setHidden:YES];
	[zoomSlider setHidden:YES];
}

-(void)arataDg:(id)sender
{
	[datePersonaleView setHidden:YES];
	[fisaView setHidden:YES];
	[rxView setHidden:YES];
	[fotoView setHidden:YES];
	[dgView setHidden:NO];
	[modelView setHidden:YES];
	[zoomSlider setHidden:YES];
	[self loadDgForPacient:[[pacienti selectedElement] objectForKey:@"id"]];
	
}

-(void)arataModel:(id)sender
{
	[datePersonaleView setHidden:YES];
	[fisaView setHidden:YES];
	[rxView setHidden:YES];
	[fotoView setHidden:YES];
	[dgView setHidden:YES];
	[modelView setHidden:NO];
	[zoomSlider setHidden:YES];
	//[self loadDgForPacient:[pacient objectForKey:@"id"]];
}


-(void)deschideDoc:(id)sender
{
	NSOpenPanel *op = [NSOpenPanel openPanel];
	[op runModal];
}

-(IBAction) fereastraNou:(id)sender
{
	//Controller *con  = [[Controller alloc] init];
	//[con retain];
	[NSBundle loadNibNamed:@"MainMenu" owner:self];
	//[con sh
}



-(void) updateData:(id)sender
{
	[pacienti unlockTimerFireMethod:sender];
	[self loadPacienti];
	
	if(![fisaView isHidden])
	{
		[fisa unlockTimerFireMethod:sender];
		//[self loadFisaForPacient:[[pacienti selectedElement] objectForKey:@"id"]];
		//[fisa reloadData];
	}
	else if(![fotoView isHidden])
	{
		[poze unlockTimerFireMethod:sender];
	}
}

- (void)unlockTimerFireMethod:(NSTimer*)theTimer
{
	[self performSelector:@selector(updateData:) withObject:theTimer];
}

- (void)timerFireMethod:(NSTimer*)theTimer
{

//	NSThread *t = [[NSThread alloc] initWithTarget:self selector:@selector(updateData:) object:self];
//	[t start];
	//[self performSelectorInBackground:@selector(updateData:) withObject:self];
	//[self performSelector:@selector(updateData:) withObject:self];
	
}

-(NSArray*) pac
{
	
	if(!_pac) _pac = [[NSMutableArray alloc] init];
	return [[_pac retain] autorelease];
	 

}

-(void)setPac:(NSMutableArray*) p
{
	if(_pac != p)
	{
		[_pac release];
		_pac = [p mutableCopy];
	}
}

-(NSMutableArray*) grupPoze
{
	
	if(!poze) [[NSMutableArray alloc] initWithObjects:@"mumu", @"lala", nil];  
	return [poze grupPoze];
}

-(void) setGrupPoze:(NSMutableArray*) array
{
	if(_grupPoze) [_grupPoze release];
	_grupPoze = array;
	[_grupPoze retain];
}

-(IBAction) arataGrupPoze:(id)sender
{
	[poze setGrupSelectat:[[sender selectedItem] title]];
	//[pozeAC setContent:[poze poze]];
	//[self arataFoto:self];
	[self loadFoto:[[pacienti selectedElement] objectForKey:@"id"]];
}

@end
